package com.xiaoyuanxing.demo.service.impl;

import com.xiaoyuanxing.demo.entity.Account;
import com.xiaoyuanxing.demo.entity.AccountInfo;
import com.xiaoyuanxing.demo.mapper.AccountInfoMapper;
import com.xiaoyuanxing.demo.mapper.AccountMapper;
import com.xiaoyuanxing.demo.service.AccountService;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;

/*
 **@author LuoShengYing
 **@date 2021/5/22
 */
@Service("accountService")
public class AccountServiceImpl implements AccountService {
    @Resource
    private AccountMapper accountMapper;

    @Resource
    private AccountInfoMapper accountInfoMapper;

    @Override
    public Account selectByOpenID(String openID) {
        return  accountMapper.selectByOpenID(openID);
    }

    @Override
    public AccountInfo selectAccountInfoByAccountID(long accountID) {
        return accountInfoMapper.selectByAccountID(accountID);
    }

    @Override
    public int register(String openID,String avatarUrl, String nickname, String sex, String studentID, String trueName, int schoolID, String collegeName) {
        // 判断数据库中是否存在相同openID的数据，如果存在返回-1
        if (!ObjectUtils.isEmpty(accountMapper.selectByOpenID(openID)) ){
            return -1;
        }
        // 数据库中不存在相同的openID数据，则开始新增Account数据
        // 新建Account对象，存储openID和运行accountMapper.insertAccount()后自增的accountID
        Account account = new Account();
        account.setWx_openID(openID);
        accountMapper.insertAccount(account);
        // 随后新增AccountInfo数据
        // 新建AccountInfo对象
        AccountInfo accountInfo = new AccountInfo();
        accountInfo.setAccountID(account.getAccountID());
        accountInfo.setAvatarUrl(avatarUrl);
        accountInfo.setNickname(nickname);
        accountInfo.setSex(sex);
        accountInfo.setStudentID(studentID);
        accountInfo.setTrueName(trueName);
        accountInfo.setSchoolID(schoolID);
        accountInfo.setCollegeName(collegeName);
        if (accountInfoMapper.insertAccountInfo(accountInfo)){
            // Account和AccountInfo均新增成功后，返回1
            return 1;
        }
        return 0;
    }


}
